package cn.virens.dd.execute;

import java.util.List;
import java.util.Queue;

import cn.virens.dd.Strategy;
import cn.virens.dd.StrategyManageImpl;
import cn.virens.dd.StrategyValue;

public class ExecuteWorkStrategy extends ExecuteWork<StrategyManageImpl, Strategy> {

	public ExecuteWorkStrategy(Integer queueSize, Integer queueMax) {
		super(queueSize, queueMax);
	}

	@Override
	protected ExecuteResult execute0(StrategyManageImpl manage, Queue<Strategy> queue) {
		ExecuteWorkStrategyTasks execute = manage.getExecutor2();

		ExecuteResult result = new ExecuteResult();

		Strategy queueStrategy = null;
		// 如果策略条件满足 就批量执行策略下的所有任务，并获取异常结果集
		while ((queueStrategy = queue.poll()) != null) {
			StrategyValue value = manage.getValue(queueStrategy);

			// 根据策略获取对应的条件，并判断策略条件是够满足
			if (value != null && queueStrategy.filter(value)) {

				// 在异步线程池中批量执行策略下的所有任务，并获取返回值
				result.execute(queueStrategy, (strategy) -> {
					return execute(execute, strategy, value);
				});
			}
		}

		return result;
	}

	private List<Exception> execute(ExecuteWorkStrategyTasks execute, Strategy strategy, StrategyValue value) {
		return execute.execute(execute.warp(strategy, value), buildQueue(strategy.task()));
	}
}
